
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from alipay.aop.api.request.AlipayTradeWapPayRequest import AlipayTradeWapPayRequest
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
from fastapi import Depends, Request
from typing import Annotated
from alipay_utils import alipay_client,pay_controller, is_mobile_device, SuccessResponse, NotifyResponse
# http://127.0.0.1:9000/create_payment?price=11
    
async def call_create_payment(request: Request, price: int):
    transaction = pay_controller.create_transaction(price)
    
    model = AlipayTradePagePayModel()
    model.out_trade_no = transaction.out_trade_no
    model.total_amount = str(price)
    model.subject = "商品购买"
    if is_mobile_device(request):
        model.product_code = "QUICK_WAP_WAY"
        # 创建支付请求
        _request = AlipayTradeWapPayRequest(biz_model=model)
        # 设置异步通知接收地址
        _request.notify_url = f"/notify"
        # 设置同步返回地址
        _request.return_url = f"/success"
    else:
        model.product_code = "FAST_INSTANT_TRADE_PAY"
        # 创建支付请求
        _request = AlipayTradePagePayRequest(biz_model=model)
        # 设置异步通知接收地址
        _request.notify_url = f"/notify"
        # 设置同步返回地址
        _request.return_url = f"/success"

    # 获取支付链接
    response = alipay_client.page_execute(_request, http_method="GET")
    
    # 重定向到支付宝支付页面
    print(response)
    return RedirectResponse(url=response)

async def call_payment_success(request: Request, params: SuccessResponse):
    transaction = pay_controller.success(params.out_trade_no)
    if transaction:
        return {"message": "支付成功，请返回主页"}
    return {"message": "支付失败"}

async def call_payment_notify(request: Request, data: NotifyResponse):
    transaction = pay_controller.success(data.out_trade_no)
    if transaction:
        return {"message": "notify"}
    return {"message": "notify"}

app = FastAPI()

# https://erciyuan000.jw238.site/api/alipay/create_payment?order_type=monthly
@app.get("/create_payment")
async def create_payment(request: Request, price: str):
    return await call_create_payment(request, int(price))

@app.get("/success")
async def success(request: Request, params: Annotated[SuccessResponse, Depends()]):
    return await call_payment_success(request, params)

@app.post("/notify")
async def notify(request: Request):
    form_data = await request.form()
    data = NotifyResponse(**dict(form_data))
    return await call_payment_notify(request, data)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=9000)